package ltd.bugs.tool.signature.formatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;

import ltd.bugs.tool.signature.attribute.SignatureAttribute;
import ltd.bugs.tool.signature.utils.IOUtils;

/**
 * @author zhengzhq
 * @Title: ResultFormatUtils
 * @Description: 针对图片做格式化处理
 * @date 2018/8/30下午2:51
 */
public class ResultFormatUtils {

  private static Logger logger = LoggerFactory.getLogger(ResultFormatUtils.class);

  /**
   * 格式化签名图片
   *
   * @param image  图片
   * @param extras 扩展信息
   * @return String 返回对应的值
   */
  public static String format(ResultFormatter formatter, BufferedImage image,
                              Map<String, Object> extras) {
    if (formatter == ResultFormatter.DIRECT_WRITE_TO_DISK) {
      return writeToDisk(image, extras);
    }

    return formatBase64(image, extras);
  }

  private static String formatBase64(BufferedImage image,
                                     Map<String, Object> extras) {
    ByteArrayOutputStream outputStream = null;
    try {
      outputStream = new ByteArrayOutputStream();
      ImageIO.write(image, "PNG", outputStream);
      BASE64Encoder encoder = new BASE64Encoder();

      return encoder.encode(outputStream.toByteArray());
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      IOUtils.close(outputStream);
    }
  }

  private static String writeToDisk(BufferedImage image,
                                    Map<String, Object> extras) {
    if (extras == null || !extras.containsKey(SignatureAttribute.WRITE_TO_DISK_PATH)) {
      logger.warn("unexpected param! please check if you have pass filePath!");

      throw new IllegalArgumentException("invalid params.");
    }

    String filePath = (String) extras.get(SignatureAttribute.WRITE_TO_DISK_PATH);
    try {
      ImageIO.write(image, "PNG", new File(filePath));

      return filePath;
    } catch (IOException e) {
      logger.error("signature file write to disk fail!", e);
      // 包装成运行时异常抛出
      throw new RuntimeException(e);
    }
  }
}
